package Common

import (
	_ "github.com/go-sql-driver/mysql"
	//`github.com/jinzhu/gorm`
	"github.com/tietang/dbx"
	"time"
)

type Mysqldb struct {
	Database *dbx.Database
	//GormDb 		*gorm.DB
}

//单例
var G_MYSQLDB *Mysqldb

func NewMysqldb() (err error) {
	var (
		maxOpenConns    int
		connMaxLifetime int
		settings        dbx.Settings
		db              *dbx.Database
	)
	if maxOpenConns, err = G_CONF.Int("MYSQL.max"); err != nil {
		return
	}
	if connMaxLifetime, err = G_CONF.Int("MYSQL.timeout"); err != nil {
		return
	}
	settings = dbx.Settings{
		DriverName:      "mysql",
		User:            G_CONF.String("MYSQL.user"),
		Password:        G_CONF.String("MYSQL.password"),
		Database:        G_CONF.String("MYSQL.database"),
		Host:            G_CONF.String("MYSQL.host"),
		MaxOpenConns:    maxOpenConns,
		MaxIdleConns:    2,
		ConnMaxLifetime: time.Minute * time.Duration(connMaxLifetime),
		Options: map[string]string{
			"charset":   "utf8",
			"parseTime": "true",
		},
	}
	if db, err = dbx.Open(settings); err != nil {
		return
	}
	G_MYSQLDB = &Mysqldb{Database: db}
	return
}

//Gorm
func initMysql() (err error) {
	//var(
	//	db *gorm.DB
	//	conectStr string
	//)
	//conectStr=G_CONF.String("MYSQL.user")+":"+G_CONF.String("MYSQL.password")+"@tcp("+G_CONF.String("MYSQL.host")+")/"+G_CONF.String("MYSQL.database")+"?charset=utf8&parseTime=True&loc=Local"
	//if db, err = gorm.Open("mysql",conectStr );err!=nil{
	//	return
	//}
	//G_MYSQLDB=&Mysqldb{GormDb:db}
	return
}
